package com.example.sms_listener

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.IBinder
import android.provider.Telephony
import android.util.Log
import androidx.core.app.NotificationCompat
import io.flutter.plugin.common.EventChannel

/**
 * SMS监听前台服务
 * 
 * 用于在后台保持SMS监听功能
 */
class SmsListenerService : Service() {
    
    companion object {
        private const val TAG = "SmsListenerService"
        private const val NOTIFICATION_ID = 1
        private const val CHANNEL_ID = "SMS_LISTENER_SERVICE"
        private const val CHANNEL_NAME = "SMS监听服务"
        
        // 服务状态
        var isRunning = false
            private set
        
        // 事件流处理器
        var eventStreamHandler: SmsEventStreamHandler? = null
    }
    
    private var smsReceiver: SmsReceiver? = null
    
    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "SMS监听服务已创建")
    }
    
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "SMS监听服务开始")
        
        // 创建通知渠道
        createNotificationChannel()
        
        // 启动前台服务
        startForeground(NOTIFICATION_ID, createNotification())
        
        // 注册SMS接收器
        registerSmsReceiver()
        
        isRunning = true
        return START_STICKY // 服务被杀死后会重新启动
    }
    
    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "SMS监听服务已销毁")
        
        // 取消注册SMS接收器
        unregisterSmsReceiver()
        
        isRunning = false
    }
    
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
    
    /**
     * 创建通知渠道
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME,
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "SMS监听服务通知"
                setShowBadge(false)
                enableVibration(false)
                enableLights(false)
            }
            
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }
    
    /**
     * 创建前台服务通知
     */
    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("SMS监听服务")
            .setContentText("正在后台监听短信...")
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setOngoing(true)
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .build()
    }
    
    /**
     * 注册SMS接收器
     */
    private fun registerSmsReceiver() {
        try {
            Log.d(TAG, "注册SMS接收器，eventStreamHandler: $eventStreamHandler")
            smsReceiver = SmsReceiver(eventStreamHandler)
            val intentFilter = IntentFilter(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)
            intentFilter.priority = 1000
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                registerReceiver(smsReceiver, intentFilter, Context.RECEIVER_EXPORTED)
            } else {
                registerReceiver(smsReceiver, intentFilter)
            }
            
            Log.d(TAG, "SMS接收器已注册")
        } catch (e: Exception) {
            Log.e(TAG, "注册SMS接收器失败", e)
        }
    }
    
    /**
     * 取消注册SMS接收器
     */
    private fun unregisterSmsReceiver() {
        try {
            smsReceiver?.let { receiver ->
                unregisterReceiver(receiver)
                smsReceiver = null
                Log.d(TAG, "SMS接收器已取消注册")
            }
        } catch (e: Exception) {
            Log.e(TAG, "取消注册SMS接收器失败", e)
        }
    }
} 